<template>
  <el-dialog
    title="选择专家"
    :visible.sync="dialogVisible"
    width="80%"
    :before-close="handleClose"
    @open="handleOpen"
  >
    <div class="expert-selector-container">
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索专家昵称或ID"
          prefix-icon="el-icon-search"
          style="width: 300px;"
          @input="handleSearch"
          @change="handleSearch"
        />
        <el-button type="primary" @click="handleSelectAll">
          {{ isAllSelected ? '取消全选' : '全选' }}
        </el-button>
        <el-button @click="handleClearSelection">清空选择</el-button>
      </div>

      <!-- 已选择专家显示 -->
      <div v-if="selectedExperts.length > 0" class="selected-experts">
        <h4>已选择专家 ({{ selectedExperts.length }})</h4>
        <div class="selected-list">
          <el-tag
            v-for="expert in selectedExperts"
            :key="expert.expert_id"
            closable
            style="margin-right: 8px; margin-bottom: 8px;"
            @close="handleRemoveExpert(expert)"
          >
            {{ expert.nickname }} (ID: {{ expert.expert_id }})
          </el-tag>
        </div>
      </div>

      <!-- 专家列表 -->
      <div class="expert-list-container">
        <el-table
          ref="expertTable"
          v-loading="loading"
          :data="filteredExpertList"
          style="width: 100%;"
          max-height="400"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
            :selectable="checkSelectable"
          />
          <el-table-column label="专家ID" prop="expert_id" width="100" align="center" />
          <el-table-column label="头像" width="80" align="center">
            <template slot-scope="{row}">
              <el-avatar :size="40" :src="row.avatar" icon="el-icon-user-solid" />
            </template>
          </el-table-column>
          <el-table-column label="昵称" prop="nickname" min-width="120" />
          <el-table-column label="推荐次数" prop="recommend_count" width="100" align="center">
            <template slot-scope="{row}">
              <span>{{ row.recommend_count || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="竞彩单关" width="100" align="center">
            <template slot-scope="{row}">
              <el-tag v-if="row.jing_dan" type="primary" size="mini">有</el-tag>
              <el-tag v-else type="info" size="mini">无</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="竞彩二串1" width="100" align="center">
            <template slot-scope="{row}">
              <el-tag v-if="row.jing_shuang" type="success" size="mini">有</el-tag>
              <el-tag v-else type="info" size="mini">无</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="竞彩三串1" width="100" align="center">
            <template slot-scope="{row}">
              <el-tag v-if="row.jing_san" type="warning" size="mini">有</el-tag>
              <el-tag v-else type="info" size="mini">无</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="让球单关" width="100" align="center">
            <template slot-scope="{row}">
              <el-tag v-if="row.rang_dan" type="primary" size="mini">有</el-tag>
              <el-tag v-else type="info" size="mini">无</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="让球二串1" width="100" align="center">
            <template slot-scope="{row}">
              <el-tag v-if="row.rang_shuang" type="success" size="mini">有</el-tag>
              <el-tag v-else type="info" size="mini">无</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="让球三串1" width="100" align="center">
            <template slot-scope="{row}">
              <el-tag v-if="row.rang_san" type="warning" size="mini">有</el-tag>
              <el-tag v-else type="info" size="mini">无</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="让分单关" width="100" align="center">
            <template slot-scope="{row}">
              <el-tag v-if="row.fen_dan" type="primary" size="mini">有</el-tag>
              <el-tag v-else type="info" size="mini">无</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="让分二串1" width="100" align="center">
            <template slot-scope="{row}">
              <el-tag v-if="row.fen_shuang" type="success" size="mini">有</el-tag>
              <el-tag v-else type="info" size="mini">无</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="让分三串1" width="100" align="center">
            <template slot-scope="{row}">
              <el-tag v-if="row.fen_san" type="warning" size="mini">有</el-tag>
              <el-tag v-else type="info" size="mini">无</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :disabled="selectedExperts.length === 0" @click="handleConfirm">
        确认选择 ({{ selectedExperts.length }})
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { zhuanjiaList } from '../../libs/api'

export default {
  name: 'ExpertSelectorDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      expertList: [],
      filteredExpertList: [],
      selectedExperts: [],
      searchKeyword: '',
      loading: false,
      isUpdatingSelection: false, // 标志位，防止在更新选择状态时触发选择变化事件
      searchTimer: null, // 搜索防抖定时器
      storageKey: 'expert_selector_selected_experts' // localStorage存储键名
    }
  },
  computed: {
    isAllSelected() {
      return this.selectedExperts.length === this.filteredExpertList.length && this.filteredExpertList.length > 0
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        this.dialogVisible = newVal
      },
      immediate: true
    },
    dialogVisible(newVal) {
      this.$emit('update:visible', newVal)
    }
  },
  beforeDestroy() {
    // 清理定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer)
    }
  },
  methods: {
    // 保存选择的专家到localStorage
    saveSelectedExpertsToStorage() {
      try {
        const expertsData = JSON.stringify(this.selectedExperts)
        localStorage.setItem(this.storageKey, expertsData)
        console.log('已保存选择的专家到localStorage:', this.selectedExperts)
      } catch (error) {
        console.error('保存专家选择到localStorage失败:', error)
      }
    },

    // 从localStorage加载选择的专家
    loadSelectedExpertsFromStorage() {
      try {
        const expertsData = localStorage.getItem(this.storageKey)
        if (expertsData) {
          this.selectedExperts = JSON.parse(expertsData)
          console.log('从localStorage加载选择的专家:', this.selectedExperts)
        }
      } catch (error) {
        console.error('从localStorage加载专家选择失败:', error)
        this.selectedExperts = []
      }
    },

    // 清空localStorage中的专家选择
    clearSelectedExpertsFromStorage() {
      try {
        localStorage.removeItem(this.storageKey)
        console.log('已清空localStorage中的专家选择')
      } catch (error) {
        console.error('清空localStorage中的专家选择失败:', error)
      }
    },
    // 打开对话框时加载数据
    async handleOpen() {
      // 先从localStorage加载之前的选择状态
      this.loadSelectedExpertsFromStorage()

      await this.loadExpertList()
      // 加载完成后设置表格选择状态
      this.$nextTick(() => {
        this.updateTableSelection()
      })
    },

    // 加载专家列表
    async loadExpertList() {
      this.loading = true
      try {
        const response = await zhuanjiaList({
          page: 1,
          page_size: 1000 // 获取所有专家
        })

        this.expertList = response.data.data || []
        this.filteredExpertList = [...this.expertList]
        console.log('加载专家列表:', this.expertList)
      } catch (error) {
        console.error('加载专家列表失败:', error)
        this.$message.error('加载专家列表失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索功能
    handleSearch() {
      // 清除之前的定时器
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }

      // 设置防抖定时器
      this.searchTimer = setTimeout(() => {
        this.performSearch()
      }, 300) // 300ms 防抖延迟
    },

    // 执行搜索
    performSearch() {
      console.log('执行搜索，当前已选择专家:', this.selectedExperts)

      if (!this.searchKeyword.trim()) {
        this.filteredExpertList = [...this.expertList]
      } else {
        const keyword = this.searchKeyword.toLowerCase()
        this.filteredExpertList = this.expertList.filter(expert =>
          expert.nickname.toLowerCase().includes(keyword) ||
          expert.expert_id.toString().includes(keyword)
        )
      }

      // 重新设置表格选择状态，保持已选择专家的选中状态
      this.$nextTick(() => {
        this.updateTableSelection()
      })
    },

    // 更新表格选择状态
    updateTableSelection() {
      console.log('更新表格选择状态，已选择专家:', this.selectedExperts)
      console.log('当前过滤后的专家列表:', this.filteredExpertList)
      // 设置标志位，防止触发选择变化事件
      this.isUpdatingSelection = true

      // 延迟执行，确保DOM更新完成
      this.$nextTick(() => {
        // 先清除当前表格的选择状态
        this.$refs.expertTable.clearSelection()

        // 再次延迟，确保clearSelection完成
        this.$nextTick(() => {
          // 然后根据已选择的专家列表重新设置选中状态
          this.filteredExpertList.forEach(row => {
            const isSelected = this.selectedExperts.some(selected => selected.expert_id === row.expert_id)
            console.log(`专家 ${row.nickname} (ID: ${row.expert_id}) 是否已选择:`, isSelected)
            if (isSelected) {
              this.$refs.expertTable.toggleRowSelection(row, true)
            }
          })

          // 延迟重置标志位，确保所有操作完成
          setTimeout(() => {
            this.isUpdatingSelection = false
            console.log('表格选择状态更新完成')
          }, 200)
        })
      })
    },

    // 表格选择变化
    handleSelectionChange(selection) {
      console.log('handleSelectionChange 被调用，isUpdatingSelection:', this.isUpdatingSelection)
      console.log('当前选择:', selection)
      console.log('当前已选择专家:', this.selectedExperts)

      // 如果正在更新选择状态，跳过处理
      if (this.isUpdatingSelection) {
        console.log('正在更新选择状态，跳过处理')
        return
      }

      // 检查是否是用户真正的选择操作
      // 如果selection为空且selectedExperts不为空，可能是搜索导致的清空，应该跳过
      if (selection.length === 0 && this.selectedExperts.length > 0) {
        console.log('检测到可能是搜索导致的清空，跳过处理')
        return
      }

      console.log('用户选择变化:', selection)

      // 获取当前页面的专家ID
      const currentPageExpertIds = this.filteredExpertList.map(expert => expert.expert_id)
      const newlySelectedIds = selection.map(expert => expert.expert_id)

      console.log('当前页面专家ID:', currentPageExpertIds)
      console.log('当前页面新选择的专家ID:', newlySelectedIds)

      // 更新选择状态：只处理当前页面可见的专家
      // 1. 移除当前页面中被取消选择的专家
      this.selectedExperts = this.selectedExperts.filter(expert => {
        if (currentPageExpertIds.includes(expert.expert_id)) {
          // 如果专家在当前页面，检查是否还在选择中
          return newlySelectedIds.includes(expert.expert_id)
        }
        // 如果专家不在当前页面，保持不变
        return true
      })

      // 2. 添加当前页面中新选择的专家
      selection.forEach(selected => {
        if (!this.selectedExperts.some(expert => expert.expert_id === selected.expert_id)) {
          this.selectedExperts.push(selected)
        }
      })

      // 保存到localStorage
      this.saveSelectedExpertsToStorage()

      console.log('选择变化后的已选择专家:', this.selectedExperts)
    },

    // 检查是否可选择
    checkSelectable(row) {
      return true
    },

    // 全选/取消全选
    handleSelectAll() {
      if (this.isAllSelected) {
        // 取消全选 - 移除当前页面的所有专家
        const currentPageExpertIds = this.filteredExpertList.map(expert => expert.expert_id)
        this.selectedExperts = this.selectedExperts.filter(expert =>
          !currentPageExpertIds.includes(expert.expert_id)
        )
        this.$refs.expertTable.clearSelection()
      } else {
        // 全选 - 添加当前页面的所有专家
        this.filteredExpertList.forEach(row => {
          if (!this.selectedExperts.some(expert => expert.expert_id === row.expert_id)) {
            this.selectedExperts.push(row)
          }
        })
        this.$refs.expertTable.toggleAllSelection()
      }
      // 保存到localStorage
      this.saveSelectedExpertsToStorage()
    },

    // 清空选择
    handleClearSelection() {
      console.log('用户主动清空所有选择')
      this.selectedExperts = []
      // 保存到localStorage
      this.saveSelectedExpertsToStorage()
      this.$refs.expertTable.clearSelection()
    },

    // 移除单个专家
    handleRemoveExpert(expert) {
      console.log('用户主动删除专家:', expert)
      this.selectedExperts = this.selectedExperts.filter(item => item.expert_id !== expert.expert_id)
      // 保存到localStorage
      this.saveSelectedExpertsToStorage()
      // 更新表格选择状态
      this.$nextTick(() => {
        this.updateTableSelection()
      })
    },

    // 确认选择
    handleConfirm() {
      if (this.selectedExperts.length === 0) {
        this.$message.warning('请至少选择一个专家')
        return
      }

      this.$emit('confirm', this.selectedExperts)
      this.handleClose()
    },

    // 关闭对话框
    handleClose() {
      this.dialogVisible = false
      // 关闭对话框时清空选择状态和localStorage
      this.selectedExperts = []
      this.clearSelectedExpertsFromStorage()
      this.searchKeyword = ''
      this.filteredExpertList = []
    }
  }
}
</script>

<style scoped>
.expert-selector-container {
  padding: 10px 0;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.selected-experts {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.selected-experts h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
}

.selected-list {
  min-height: 32px;
}

.expert-list-container {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
}

.dialog-footer {
  text-align: right;
  padding-top: 10px;
}

/* 表格样式优化 */
.el-table {
  font-size: 13px;
}

.el-table .el-table__header th {
  background: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

.el-table .el-table__row:hover {
  background: #f5f7fa;
}

/* 标签样式 */
.el-tag {
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .expert-selector-container {
    padding: 5px 0;
  }

  .search-container {
    flex-wrap: wrap;
    gap: 8px;
  }

  .search-container .el-input {
    width: 100% !important;
    max-width: 300px;
  }
}
</style>
